package cn.gqr.config;


import cn.gqr.service.impl.ClientDetailsServiceImpl;
import cn.gqr.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer
public class SoBookAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private AuthenticationManager authenticationManagerBean;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired  //客户端实现类
    private ClientDetailsServiceImpl clientDetailsService;

    //放行两个端点
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                // 允许所有人访问令牌获取token不进行拦截
                .tokenKeyAccess("permitAll()")
                // 已验证的客户端才能请求check_token
                .checkTokenAccess("isAuthenticated()")
                //允许通过表单实现客户端认证
                .allowFormAuthenticationForClients();
    }


    //客户端配置
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 配置基于jdbc的ClientDetailsService，用于加载客户端信息
        clients.withClientDetails(clientDetailsService);
    }

    //支持密码模式
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("进入 AuthorizationServerEndpointsConfigurer ");
        endpoints
                //通过redis保存token
                .tokenStore(new RedisTokenStore(redisConnectionFactory))
                //认证管理器
                .authenticationManager(authenticationManagerBean)
                // 允许 GET、POST 请求获取 token，即访问端点：oauth/token
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST)
                // 用户管理服务
                .userDetailsService(userDetailsService);
    }


}
